import React, { useState, useEffect } from 'react';
import { DetailView as DetailViewModel } from '../core/DetailView';
import PropertyEditorComponent from './PropertyEditorComponent';
import { Tabs } from 'antd';
import ListView from './ListView';
import { Action } from '../core/Action';
import { ListView as ListViewModel } from '../core/ListView';
import './DetailView.less';

interface DetailViewProps {
  model: DetailViewModel;
}

/**
 * DetailView Component - React component for the DetailView core class
 */
const DetailView: React.FC<DetailViewProps> = ({ model }) => {
  const [formData, setFormData] = useState<Record<string, any>>(model.currentObject || {});
  const [activeTab, setActiveTab] = useState<string>('main');

  // Update form data when model's currentObject changes
  useEffect(() => {
    console.log('DetailView component: model =', model);
    console.log('DetailView component: model.currentObject =', model.currentObject);
    console.log('DetailView component: model.propertyEditors =', model.propertyEditors);
    
    setFormData(model.currentObject || {});
  }, [model.currentObject]);

  // Handle property value changes
  const handleValueChange = (propertyName: string, newValue: any) => {
    console.log(`DetailView: Property ${propertyName} changed to:`, newValue);
    
    setFormData((prevData: Record<string, any>) => {
      const newFormData = {
        ...prevData,
        [propertyName]: newValue
      };
      
      // Update the model's object with the new data
      model.setObject(newFormData);
      
      return newFormData;
    });
  };

  // Set up handlers for saving and canceling
  const handleSave = () => {
    // Validate all editors before saving
    if (model.validateAllEditors()) {
      // Update the model's object with form data
      model.setObject(formData);
      
      // Find the save action and execute it
      const saveAction = model.controllers.flatMap(c => c.actions)
        .find(action => action.id.includes('Save'));
      
      if (saveAction) {
        saveAction.execute();
      }
    } else {
      // Show error message
      console.error('Validation errors:', model.validationErrors);
    }
  };

  const handleCancel = () => {
    // Reset form data to model's current object
    setFormData(model.currentObject || {});
    
    // Find the cancel action and execute it
    const cancelAction = model.controllers.flatMap(c => c.actions)
      .find(action => action.id.includes('Cancel'));
    
    if (cancelAction) {
      cancelAction.execute();
    }
  };

  // Get all related views
  const relatedViews = model.relatedViews || {};
  const relatedViewKeys = Object.keys(relatedViews);

  // Prepare tabs for the detail view
  const getTabs = () => {
    const items = [
      {
        key: 'main',
        label: 'Main',
        children: (
          <div className="property-editors-container">
            {model.propertyEditors.length > 0 ? (
              model.propertyEditors.map((editor, index) => (
                <PropertyEditorComponent
                  key={index}
                  editor={editor}
                  value={formData[editor.propertyName]}
                  onChange={(newValue) => handleValueChange(editor.propertyName, newValue)}
                />
              ))
            ) : (
              <div className="empty-editors-message">
                <p>No property editors defined for this view.</p>
                <p>Check that the property editors are being created correctly.</p>
                <div className="debug-info">
                  <h4>Debug Information</h4>
                  <p>View Type: {model.constructor.name}</p>
                  <p>View ID: {model.id}</p>
                  <p>View Caption: {model.caption}</p>
                  <p>Object Data:</p>
                  <pre>{JSON.stringify(formData, null, 2)}</pre>
                  <p>Validation Errors:</p>
                  <pre>{JSON.stringify(model.validationErrors, null, 2)}</pre>
                </div>
              </div>
            )}
          </div>
        )
      }
    ];

    // Add tabs for related views
    relatedViewKeys.forEach(key => {
      const relatedView = relatedViews[key];
      if (relatedView instanceof ListViewModel) {
        items.push({
          key,
          label: relatedView.caption,
          children: <ListView model={relatedView} />
        });
      } else if (relatedView instanceof DetailViewModel) {
        items.push({
          key,
          label: relatedView.caption,
          children: <DetailView model={relatedView} />
        });
      }
    });

    return items;
  };

  // Get all actions from controllers
  const getActions = () => {
    return model.controllers.flatMap(controller => controller.actions);
  };

  return (
    <div className="mini-xaf-detail-view">
      {/* Action buttons */}
      <div className="action-buttons">
        {getActions().filter(action => action.visible).map((action: Action, index: number) => (
          <button 
            key={index}
            onClick={() => action.execute()}
            disabled={!action.enabled}
            className="action-button"
          >
            {action.imageUrl && (
              <img src={action.imageUrl} alt="" className="action-icon" />
            )}
            {action.caption}
          </button>
        ))}
      </div>

      {/* Content area */}
      {relatedViewKeys.length > 0 ? (
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={getTabs()}
        />
      ) : (
        <div className="property-editors-container">
          {model.propertyEditors.length > 0 ? (
            model.propertyEditors.map((editor, index) => (
              <PropertyEditorComponent
                key={index}
                editor={editor}
                value={formData[editor.propertyName]}
                onChange={(newValue) => handleValueChange(editor.propertyName, newValue)}
              />
            ))
          ) : (
            <div className="empty-editors-message">
              <p>No property editors defined for this view.</p>
              <p>Check that the property editors are being created correctly.</p>
              <div className="debug-info">
                <h4>Debug Information</h4>
                <p>View Type: {model.constructor.name}</p>
                <p>View ID: {model.id}</p>
                <p>View Caption: {model.caption}</p>
                <p>Object Data:</p>
                <pre>{JSON.stringify(formData, null, 2)}</pre>
                <p>Validation Errors:</p>
                <pre>{JSON.stringify(model.validationErrors, null, 2)}</pre>
              </div>
            </div>
          )}
        </div>
      )}
      
      <div className="form-buttons">
        <button onClick={handleSave} className="save-button">Save</button>
        <button onClick={handleCancel} className="cancel-button">Cancel</button>
      </div>
    </div>
  );
};

export default DetailView;
